package com.info33.platform.config.db;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.info33.platform.system.vo.SysUserVO;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.Date;

/**
 * 注入公共字段自动填充,任选注入方式即可
 *
 * @author Administrator
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 获取当前用户 租户用户 id 或 租户 id
     *
     * @param flag true/返回租户 id、false/返回租户用户 id
     * @return -
     */
    private Long getId(Boolean flag) {
        Object principal = SecurityUtils.getSubject().getPrincipal();
        if (ObjectUtils.isEmpty(principal)) {
            return 1L;
        }
        SysUserVO vo = (SysUserVO) principal;
        if (Boolean.TRUE.equals(flag)) {
            return vo.getTenant().getId();
        }
        if (!ObjectUtils.isEmpty(vo.getSysTenantUserVO())) {
            return ((SysUserVO) principal).getSysTenantUserVO().getId();
        }
        if (!ObjectUtils.isEmpty(vo.getAppTenantUserVO())) {
            return ((SysUserVO) principal).getAppTenantUserVO().getId();
        }
        return 1L;
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        // 版本号3.0.6以及之前的版本
        Date date = new Date();
        Long id = getId(Boolean.FALSE);
        Long tid = getId(Boolean.TRUE);
        this.setFieldValByName("createBy", id, metaObject);
        this.setFieldValByName("createDate", date, metaObject);
        this.setFieldValByName("updateBy", id, metaObject);
        this.setFieldValByName("updateDate", date, metaObject);
        this.setFieldValByName("uuid", IdUtil.simpleUUID(), metaObject);
        this.setFieldValByName("version", 1, metaObject);
        this.setFieldValByName("status", 1, metaObject);
        this.setFieldValByName("tenantId", tid, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 版本号3.0.6以及之前的版本
        this.setFieldValByName("updateBy", getId(Boolean.FALSE), metaObject);
        this.setFieldValByName("updateDate", new Date(), metaObject);
    }

}
